<template>
  <el-dropdown-item icon="el-icon-lock" @click.native="dialogVisible = true">修改密码
    <el-dialog title="修改密码" :visible.sync="dialogVisible" append-to-body width="30%" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules">
        <el-form-item prop="phone">
          <el-input v-model="form.phone" prefix-icon="el-icon-phone" :readonly=true></el-input>
        </el-form-item>
        <el-form-item prop="newPassword">
          <el-input v-model="form.newPassword" placeholder="请输入新密码" prefix-icon="el-icon-lock" show-password></el-input>
        </el-form-item>
        <el-form-item prop="checkPassword">
          <el-input v-model="form.checkPassword" placeholder="请再次输入密码" prefix-icon="el-icon-lock"
            show-password></el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <div style="display: flex; align-items: center">
            <el-input v-model="form.captcha" placeholder="6 位短信验证码" style="margin-right: 10px"
              prefix-icon="el-icon-chat-line-square"></el-input>
            <GetCaptchaButton :phone="form.phone"></GetCaptchaButton>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="edit">确 定</el-button>
      </span>
    </el-dialog>
  </el-dropdown-item>
</template>

<script>
import { validatePassword } from "@/utils/validate";
import { updatePasswordByCaptcha } from "@/api/auth/user";
import GetCaptchaButton from "@/components/GetCaptchaButton.vue";
import Cookies from "js-cookie";

export default {
  name: "EditPassword",
  components: { GetCaptchaButton },
  data() {
    const validateCheckPassword = (rule, value, callback) => {
      if (value !== this.form.newPassword || value === '') {
        callback(new Error('两次输入密码不一致'))
      } else {
        callback()
      }
    }
    return {
      dialogVisible: false,
      user: {},
      form: {},
      rules: {
        newPassword: [{ required: true, trigger: 'blur', validator: validatePassword }],
        checkPassword: [{ required: true, trigger: 'blur', validator: validateCheckPassword }]
      }
    }
  },
  methods: {
    edit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          updatePasswordByCaptcha(this.form).then(res => {
            if (res.data.code === 200) {
              this.dialogVisible = false
              this.$message.success(res.data.message)
            } else {
              // this.$message.error(res.data.message)
            }
          })
        } else {
          return false
        }
      })
    }
  },
  created() {
    this.user = JSON.parse(Cookies.get("user"))
    this.form = {
      phone: this.user.phone,
      newPassword: '',
      checkPassword: '',
      captcha: ''
    }
  }
}
</script>

<style scoped></style>
